package com.example.mybatis.utils;

import com.example.mybatis.annotation.ExcelColumn;
import com.example.mybatis.annotation.ExcelSheet;
import com.example.mybatis.model.ColumnInfo;
import com.example.mybatis.model.SheetInfo;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.List;

public class AnnotationSheetUtil {

    public static SheetInfo initSheetInfo(Class clazz){
        SheetInfo sheetInfo=null;
        if(clazz.isAnnotationPresent(ExcelSheet.class)){
            Annotation annotation = clazz.getDeclaredAnnotation(ExcelSheet.class);
            ExcelSheet sheetAnnotation = (ExcelSheet) annotation;
            String sheetName = sheetAnnotation.name();
            if("".equals(sheetName)){
                sheetName = sheetAnnotation.value();
            }
            if("".equals(sheetName)){
                sheetName = clazz.getSimpleName();
            }
            String voClass = sheetAnnotation.voClass();
            if("".equals(voClass)){
                voClass = clazz.getName();
            }
            sheetInfo = new SheetInfo(sheetName,voClass);
            List<ColumnInfo> columnInfos = sheetInfo.getColumns();
            Field[] fields = clazz.getDeclaredFields();
            for(Field field: fields){
                if(field.isAnnotationPresent(ExcelColumn.class)){
                    Annotation columnAnnotation = field.getDeclaredAnnotation(ExcelColumn.class);
                    ExcelColumn excelColumnAnnotation = (ExcelColumn) columnAnnotation;
                    String propName = excelColumnAnnotation.name();
                    if("".equals(propName)){
                        propName = field.getName();
                    }
                    String displayName = excelColumnAnnotation.displayName();
                    String type = excelColumnAnnotation.type();
                    Integer width = excelColumnAnnotation.width();
                    ColumnInfo columnInfo = new ColumnInfo(propName,displayName,type,width);
                    String format = excelColumnAnnotation.format();
                    if(!"".equals(format)){
                        columnInfo.setFormat(format);
                    }
                    Integer order = excelColumnAnnotation.order();
                    columnInfo.setOrder(order);
                    columnInfos.add(columnInfo);
                }
            }
            columnInfos.sort(Comparator.comparing(item->{
                return item.getOrder();
            }));
        }
        return sheetInfo;
    }
}
